#!/usr/bin/env python
#-*- coding:utf-8 -*-

import logging

VERSION = '20100408'
logger = logging.getLogger('shorp.node')

class Node:
    tokenkeys = ['+', ':', '#', '.']
    scriptkey = '<'
    childkey = '>'
    
    def __init__(self):
        self.atidx = 0
        self.attrs = {}
    
    def setAttr(self, attr, value):
        if self.attrs.has_key(attr):
            return False
        else:
            self.attrs[attr] = value
            return True
            
    def addAttr(self, attr, value, delimiter=' '):
        if self.attrs.has_key(attr):
            v = self[attr] + delimiter + value
            self[attr] = v
        else:
            self.attrs[attr] = value
    
    def hasAttr(self, attr):
        return self.attrs.has_key(attr)
        
    def getAttr(self, attr):
        if self.hasAttr(attr):
            return self.attrs[attr]
        else:
            return ''
            
    def setAtAttr(self, value):
        ret = self.setAttr('@'+str(self.atidx), value)
        if ret:
            self.atidx = self.atidx + 1
        return ret
        
    def getAtAttr(self, idx):
        if idx <= self.atidx:
            return self.getAttr('@'+str(idx))
        return ''
    
    def getAttrs(self, includeAt = False):
        attrs = {}
        for k,v in self.attrs.iteritems():
            if k not in self.tokenkeys and k!=self.childkey and \
                k!=self.scriptkey and (includeAt or k[0]!='@'):
                attrs[k] = v
        return attrs
        
    def setScript(self, script):
        return self.setAttr(self.scriptkey, script)
        
    def getScript(self):
        return self.getAttr(self.scriptkey)
        
    def addChild(self, child):
        if '>' not in self.attrs.keys():
            self.attrs['>'] = [child]
        else:
            self.attrs['>'].append(child)
    
    def getChilds(self):
        if self.childkey in self.attrs:
            return self.attrs[self.childkey]
        else:
            return {}
    
    def getTokens(self):
        tokens = []
        for key in self.tokenkeys:
            value = self.getAttr(key)
            if value!='': tokens.append((key,value))
        return tokens
        
    
    def isEmpty(self):
        return len(self.attrs)==0
    
    def __repr__(self):
        return self.__str__()
        
    def __str__(self):
        return str(self.attrs)
